package com.bj58.groupbuy.action.threads;

import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import com.bj58.groupbuy.action.model.IRReport;
import com.bj58.groupbuy.action.model.UserSubMailVo;
import com.bj58.groupbuy.action.service.IRReportService;
import com.bj58.groupbuy.action.service.IntReportMainService;
import com.bj58.groupbuy.action.service.UserSubMailService;
import com.bj58.groupbuy.action.util.DateUtil;
import com.bj58.groupbuy.action.util.ExcelUtilNew;
import com.bj58.groupbuy.action.util.FileUtil;
import com.bj58.groupbuy.action.util.MailUtil;
import com.bj58.groupbuy.action.util.MyPathUtil;
import com.bj58.groupbuy.action.util.ZipUtil;
import com.bj58.groupbuy.service.locator.ServiceLocator;
import com.bj58.groupbuy.wf.page.Paginate;

/**
 * 不断的监听，一个一个的运行 监测状态，如果运行完了，继续查询，不停的查询，如果查询为空就sleep
 * 可以由用户触发，当点击下载的时候触发，如果在运行就等待，如果不在运行就启动
 * */
public class UserDownfileThread extends Thread {
	private IRReportService iRReportService = ServiceLocator
			.get(IRReportService.class);
	private IntReportMainService intReportMainService = ServiceLocator
			.get(IntReportMainService.class);
	private UserSubMailService iRSubMailService = ServiceLocator
			.get(UserSubMailService.class);

	public static AtomicInteger threadDoneCount = new AtomicInteger();

	private UserSubMailVo irsm;

	public UserDownfileThread(UserSubMailVo irsm) {
		this.irsm = irsm;
	}

	public void run() {
		try {
			System.out.println("Thead  " + this.getId()
					+ " begin to deal subMail ,ID  is" + irsm.getId());
			int result = sendSubMail(irsm);
			if (result == 2) {
				irsm.setModTime(DateUtil.getStringDate(new Date(),
						"yyyy-MM-dd HH:mm:ss"));
				irsm.setCompTime(DateUtil.getStringDate(DateUtil.getDateAfter(new Date(), 3),
						"yyyy-MM-dd HH:mm:ss"));
				iRSubMailService.updateVo(irsm);
			}
			System.out.println("Thead  " + this.getId() + " is end ");
			threadDoneCount.getAndIncrement(); // 线程完成则在原子计数器上+1
			System.out.println(threadDoneCount.get());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("static-access")
	private int sendSubMail(UserSubMailVo vo) {
		try {
			// step 1
			StringBuffer searchCondition = new StringBuffer();
			int pagesum = 500000;

			String condition = vo.getSearchCondition();
			String hasComp = "";
			int dayRatio = vo.getDayRatio(); // 环同比标志:1包含，0不包含
			int weekRatio = vo.getWeekRatio();
			String specialValue = vo.getSearchSpeValue();
			HashMap<String, String> keyValue = new HashMap<String, String>();
			// 日期列名称,从specialValue中获取

			String dateCol = specialValue.substring(
					specialValue.lastIndexOf(":") + 1,
					specialValue.length() - 1).trim();
			String startDate = specialValue.split(";")[0].split(":")[1];
			String endDate = specialValue.split(";")[1].split(":")[1];
			Date nowDate = new Date();
			searchCondition.append(" and " + dateCol + ">='" + startDate + "'");
			searchCondition.append(" and " + dateCol + "<='" + endDate + "' ");
			searchCondition.append(condition);
			// step 2
			IRReport irReport = iRReportService.getById(vo.getReportId());
			List<String> cols = new ArrayList<String>(); // 查询字段项 -英文
			String gbs[] = null;
			if (!"".equals(vo.getSearchGroupBy())) {// groupBy占位
				gbs = vo.getSearchGroupBy().split(",");
				cols.add("groupBy");
			}
			for (String col : vo.getSearchCols().split("&")) {
				if (!"".equals(col)) {
					cols.add(col);
				}
			}

			List<String> titleList = new ArrayList<String>(); // 查询字段项 - 中文
																// 表格TITLE
			for (String title : vo.getSearchTitles().split("&")) {
				if (!"".equals(title)) {
					titleList.add(title);
				}
			}
			// 标题
			String titleDates = " ";
			if (startDate.equals(endDate)) {
				titleDates = startDate;
			} else {
				titleDates = " from " + startDate + " to " + endDate;
			}
			if (titleDates == "") {
				titleDates = DateUtil.getStringDate(nowDate, "yyyy-MM-dd");
			}
			String dirPath = MyPathUtil.getZipSavePath() + "/" +vo.getSubName();
			File file = new File(dirPath);
			if (file.exists() && file.isDirectory()) {
				FileUtil.deleteDirectory(dirPath);
			}
			file.mkdirs();
			// 使用原special，不做任何更改
			Paginate<String> pList = intReportMainService.IRsearchValues(
					irReport, searchCondition.toString(), cols, null,
					vo.getSearchOrderBy(), vo.getSearchGroupBy(), 20, -1,
					specialValue, 1);
			List<String> sumitems=pList.getItems();
			if (dayRatio == 1 || weekRatio == 1){
				sumitems = new ArrayList<String>();
				// 含同环比
				if (dayRatio == 1) {
					hasComp += "dayRatio";
					
				}
				if (weekRatio == 1) {
					hasComp += ",weekRatio";
					
				}
				List<String> items = pList.getItems(); // 获得总结果集
				for (String recode : items) { // 对每一条记录提取维度值，放入对应的Map中
					StringBuilder key = new StringBuilder();
					String cells[] = recode.split(";", gbs.length + 1);
					for (int i = 0; i < gbs.length; i++) { // 维度
						key.append(cells[i].split(",")[0]);
						if (i + 1 < gbs.length)
							key.append("_");
					}
					String date = cells[0].split(",")[0];// 日期
					if (date.compareTo(startDate) >= 0&& date.compareTo(endDate) <= 0)
						sumitems.add(recode);
					keyValue.put(key.toString(), cells[gbs.length]);//keyvalue取所有的数据
				}
			}
			int k = 0;
			int beginnum = 0;
			int endnum = 0;
			while (sumitems.size() > k * pagesum) {
				beginnum = k * pagesum;
				endnum = (k + 1) * pagesum;
				if(endnum>sumitems.size())
				{
					endnum=sumitems.size();
				}
				List<String> toSendItems =sumitems.subList(beginnum,
						endnum); // 要发送的结果
				SXSSFWorkbook wwb = new SXSSFWorkbook(100000);// 内存中保留 10000
																// 条数据，以免内存溢出，其余写入
																// 硬盘
				if (null == toSendItems || toSendItems.isEmpty()) { // 要发送的数据集为空
					break;
				}

				String excelPath = dirPath + "/" +vo.getReportName()+ titleDates
						+ "-page-" + k + ".xlsx";

				int statgbsindex = 0;
				if (null != gbs) {
					for (int i = 0; i < gbs.length; i++) { // 日期维度所在位置
						if (gbs[i].equals("stat_date")
								|| gbs[i].equals("statDate")
								|| gbs[i].equals("vDate")) {
							statgbsindex = i;
							break;
						}
					}
				}
				statgbsindex=0;
				if(null !=gbs)
				{
					for (int i = 0; i < gbs.length; i++) { // 日期维度所在位置
						if (gbs[i].equals("stat_date")||gbs[i].equals("statDate")||gbs[i].equals("vDate")) {
							statgbsindex=i;
							break;
						}
					}
				}
				if ((dayRatio == 1 || weekRatio == 1) && gbs != null){	
					
					wwb = ExcelUtilNew.writeExcelCommonWithRatioSync(vo.getReportName(), null, titleList,toSendItems, keyValue, gbs.length, excelPath,dayRatio == 1 ? true : false, weekRatio == 1 ? true:false,statgbsindex);
				}else{
					int gbLength = 0 ;
					if(null != gbs ){
						gbLength = gbs.length;
					}
					System.out.println("TTTTTTTTT");
					wwb = ExcelUtilNew.writeExcelCommonWithRatioSync(vo.getReportName(), null, titleList, toSendItems,null,gbLength,excelPath,false,false,statgbsindex);
					System.out.println("TTTTTTTTT1");
				}
				
				if (wwb == null) {
					FileUtil.deleteDirectory(dirPath);
					return 1;
				} else {

					FileOutputStream os = new FileOutputStream(excelPath);
					System.out.println("TTTTTTTTT2");
					wwb.write(os);
					System.out.println("TTTTTTTTT3");
					os.close();
				}
				k++;
			}
			// 将整个文件夹压缩
			ZipUtil zip = new ZipUtil();
			String zipPath =MyPathUtil.getZipSavePath()+"/"+vo.getId()+vo.getUserId()+vo.getReportId()+".zip";
			FileUtil.deleteFile(zipPath);
			zip.createZip(zipPath, dirPath);
			
			FileUtil.DeleteFolder(dirPath);
		} catch (Exception e) {
			e.printStackTrace();
			MailUtil.javaMailSend("下载邮件发送程序报错", "下载ID为" + vo.getId(),
					"houzuoxin@58ganji.com", null);
			return 0;
		}
		/*String filenameString="";
		try {
			filenameString=java.net.URLEncoder.encode(vo.getReportName(),"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		String mailinfostr="请尽快到 http://bi.t.58.com -》 个人中心 -》 我的下载   中下载，或直接点击：<a href='http://bi.t.58.com/zipfiles/"+vo.getId()+vo.getUserId()+vo.getReportId()+".zip'>下载链接</a>"+"，该数据文件将在我们服务器上保留3天。";
		MailUtil.javaMailSend(vo.getSubName() + "下载缓冲成功",
				mailinfostr, vo.getSendEmail(), null);
		return 2;
	}

	public static void main(String[] args) throws UnsupportedEncodingException {

		
		String mailinfostr="请尽快到 http://bi.t.58.com -》 个人中心 -》 我的下载   中下载，或直接点击：<a href='http://hzx.58.com/zipfiles/398847173.zip'>下载链接</a>"+"，该数据文件将在我们服务器上保留3天。";
		/*String testString="";
		try {
			//mailinfostr=java.net.URLDecoder.decode(mailinfostr,"utf-8");
			testString=java.net.URLEncoder.encode("品类来源数据","utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block %E5%93%81%E7%B1%BB%E6%9D%A5%E6%BA%90%E6%95%B0%E6%8D%AE =<%= URLEncoder.encode("黄河","gb2312")%>
			e.printStackTrace();
		}*/
		MailUtil.javaMailSend( "下载缓冲成功",
				mailinfostr, "houzuoxin@58ganji.com", null);
		/*<a style="color:green" href="/zipfiles/847/CPC品类来源数据402.zip">已完成，点此下载。</a>
		 * finally{ System.exit(0); }
		 */
	}

}
